<template>
  <div ref="lottie"></div>
</template>
<script lang="ts" setup>
import { onMounted, useTemplateRef } from 'vue';
import lottie from 'lottie-web';
import type { AnimationConfigWithData, AnimationItem } from 'lottie-web';
import { isFunction } from 'es-toolkit';

defineOptions({
  name: 'LottieComponent',
});

const lottieRef = useTemplateRef<HTMLDivElement>('lottie');
const props = defineProps<{
  params: Partial<AnimationConfigWithData>;
  getLottie?: (lottiePKG: typeof lottie) => void;
  getAnimationInstance?: (instance: AnimationItem | null) => void;
}>();

const renderLottie = () => {
  if (!lottieRef.value) return;
  if (isFunction(props.getLottie)) {
    props.getLottie(lottie);
  }
  const instance = lottie.loadAnimation({
    container: lottieRef.value,
    renderer: 'svg',
    loop: true,
    autoplay: true,
    ...props.params,
  });
  if (isFunction(props.getAnimationInstance)) {
    props.getAnimationInstance(instance);
  }
};

onMounted(() => {
  renderLottie();
});
</script>
